/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rootfinder;

import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Administrator
 */
public class RootFinder implements Runnable {

  private static String[] users = {"root", "root", "admin"};
  private static String[] passs = {"", "root", "admin"};
  private int id;

  public RootFinder(int id) {
    this.id = id;
  }

  public void log(String msg) {
    System.out.println(id + " : " + msg);
  }

  public static void main(String[] args) {
    int size = 2;
    if(args != null && args.length > 0){
      size = Integer.parseInt(args[0]);
    }
    
    ExecutorService executor = Executors.newFixedThreadPool(size);
    for (int i = 0; i < 3; i++) {
      executor.execute(new RootFinder(i));
    }

    executor.shutdown();
    while (!executor.isTerminated()) {
    }
    System.out.println("Finished all threads");
  }

  public Connection tryHost(HostCandidate hostCandidate, String user, String pass) throws SQLException {
    String host = "jdbc:mysql://" + hostCandidate.getIp() + ":3306?connectTimeout=10";
    log("Testing > " + hostCandidate.getIp());
    return (Connection) DriverManager.getConnection(host, user, pass);
  }

  @Override
  public void run() {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("RootFinderPU");
    EntityManager em = emf.createEntityManager();
    try {

      while (true) {
        em.getTransaction().begin();
        HostCandidate host = new HostCandidate();
        Connection c = null;
        String message = "";

        HostCandidate hc = em.find(HostCandidate.class, host.getIp());
        if (hc == null) {
          for (int i = 0; i < users.length; i++) {
            try {
              c = tryHost(host, users[i], passs[i]);
              if (c != null) {
                host.setStatus("connected");
                host.setMessage(users[i] + ":" + passs[i]);
                break;
              }
            } catch (Exception e) {
              log("Error > " + e.getMessage());
              message = e.getMessage().substring(0, 40);
              host.setStatus("failed");
              host.setMessage(message);
            } finally {
              if (c != null) {
                c.close();
              }
            }
          }
          try {
            em.persist(host);
            em.getTransaction().commit();
          } catch (Exception e) {
            log("Error > " + e.getMessage());
          }
        } else {
          log("Has been checked already > " + host.getIp());
        }
      }

    } catch (Exception e) {
      log("Error Rollback> " + e.getMessage());
      em.getTransaction().rollback();
    } finally {
      em.close();
    }
  }
}
